<?php
class ImgComponent {
	function processImage(& $image, $size = array (), $path) {
		$name = explode('.', $image['name']);
		//get upload image extension name
		$imgExt = strtolower($name[count($name) - 1]);
		switch ($imgExt) {
			case 'jpg' :
				$srcImg = imagecreatefromjpeg($image['tmp_name']);
				break;
			case 'gif' :
				$srcImg = imagecreatefromgif($image['tmp_name']);
				break;
			case 'png';
				$srcImg = imagecreatefrompng($image['tmp_name']);
				break;
		}
		$oldSize['height'] = imagesy($srcImg);
		$oldSize['width'] = imagesx($srcImg);
		//reszie image
		$imageSize = $this->resizeImage($oldSize, $size);
		if ($imgExt == 'jpg') {
			$dstImg = imagecreatetruecolor($imageSize['width'], $imageSize['height']);
		} else {
			$dstImg = imagecreate($imageSize['width'], $imageSize['height']);
		}
		imagecopyresampled($dstImg, $srcImg, 0, 0, 0, 0, $imageSize['width'], $imageSize['height'], $oldSize['width'], $oldSize['height']);
		//create image
		switch ($imgExt) {
			case 'jpg' :
				imagejpeg($dstImg, $path, 100);
				break;
			case 'gif' :
				imagegif($dstImg, $path, 100);
				break;
			case 'png' :
				imagegif($dstImg, $path, 100);
				break;
		}
		return true;
	}

	function resizeImage($oldSize, $size) {
		$oldHeight = $oldSize['height'];
		$oldWidth = $oldSize['width'];
		$height = $size['height'];
		$width = $size['width'];
		$oldScale = $oldWidth / $oldHeight;
		$scale = $width / $height;
		if ($oldScale > $scale) {
			$oldHeight = $oldHeight * $width / $oldWidth;
			$oldWidth = $width;
		} else {
			$oldWidth = $oldWidth * $height / $oldHeight;
			$oldHeight = $height;
		}

		$imgSize['height'] = $oldHeight;
		$imgSize['width'] = $oldWidth;
		return $imgSize;
	}

}
?>
